package org.intelligentsia.keystone.updater;

import java.io.Serializable;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Link data structure.
 * 
 * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a>
 */
public class Link implements Serializable {

	private static final long	serialVersionUID	= -7964728817273777702L;
	private String				name;
	private int					version;
	private String				url;
	private String				checksum;
	private String				description;

	public Link() {
		super();
	}

	public Link(final String name, final int version, final String url) {
		this(name, version, url, null);
	}

	public Link(final String name, final int version, final String url, final String checksum) {
		setName(name);
		setVersion(version);
		setUrl(url);
		setChecksum(checksum);
	}

	/**
	 * @param json
	 * @throws JSONException
	 *             if name or url are not present in json fragment
	 */
	public Link(final JSONObject json) throws JSONException {
		super();
		setName(json.optString("name", null));
		setVersion(json.optInt("version", 0));
		setUrl(json.optString("url", null));
		setChecksum(json.optString("checksum", null));
		setDescription(json.optString("description", null));
	}

	public final String getName() {
		return name;
	}

	public final void setName(final String name) {
		this.name = name != null ? name.trim() : name;
	}

	public final String getDescription() {
		return description;
	}

	public final void setDescription(final String description) {
		this.description = description;
	}

	public final String getUrl() {
		return url;
	}

	public final void setUrl(final String url) {
		this.url = url != null ? url.trim() : url;
	}

	public final int getVersion() {
		return version;
	}

	public final void setVersion(final int version) {
		this.version = version;
	}

	public final String getChecksum() {
		return checksum;
	}

	public final void setChecksum(final String checksum) {
		this.checksum = checksum != null ? checksum.trim() : checksum;
	}

	@Override
	public String toString() {
		return "Link{" + "version=" + version + ", url=" + url + ", checksum=" + checksum + '}';
	}

	@Override
	public boolean equals(final Object obj) {
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		final Link other = (Link) obj;
		if ((name == null) ? (other.name != null) : !name.equals(other.name)) {
			return false;
		}
		if (version != other.version) {
			return false;
		}
		if ((url == null) ? (other.url != null) : !url.equals(other.url)) {
			return false;
		}
		if ((checksum == null) ? (other.checksum != null) : !checksum.equals(other.checksum)) {
			return false;
		}
		return true;
	}

	@Override
	public int hashCode() {
		int hash = 3;
		hash = 43 * hash + (name != null ? name.hashCode() : 0);
		hash = 43 * hash + version;
		hash = 43 * hash + (url != null ? url.hashCode() : 0);
		hash = 43 * hash + (checksum != null ? checksum.hashCode() : 0);
		return hash;
	}
}
